package com.java.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.business.dao.MaintainRecordMapper;
import com.java.business.dao.WorkInfoDao;
import com.java.business.model.MaintainRecord;
import com.java.business.model.WorkInfo;
import com.java.business.service.WorkInfoService;
import com.java.common.model.Result;
import com.java.userservice.model.User;
import com.java.userservice.service.api.UserServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WorkInfoServiceImpl implements WorkInfoService {

    @Autowired
    private WorkInfoDao workInfoDao;

    @DubboReference
    private UserServiceApi userServiceApi;

    @Autowired
    private MaintainRecordMapper maintainRecordMapper;

    @Override
    public Result save(WorkInfo workInfo) {
        workInfoDao.save(workInfo);
        return Result.success();
    }

    @Override
    public Result modify(WorkInfo workInfo) {
        workInfo.setAssignTime(new Date());
        workInfoDao.modify(workInfo);
        return Result.success();
    }

    @Override
    public Result remove(int[] ids) {
        for (int id : ids){
            workInfoDao.remove(id);
        }
        return Result.success();
    }

    @Override
    public Result list(WorkInfo workInfo) {
        PageHelper.startPage(workInfo.getPageNum(), workInfo.getPageSize());

        List<WorkInfo> list = workInfoDao.list(workInfo);
            if (list.size() != 0){
                for (WorkInfo info : list) {
                    if (info.getUserId() != null){
                        if (!info.getUserId().equals("")){
                            User user = userServiceApi.listAll(Integer.parseInt(info.getUserId()));
                            info.setUser(user);
                        }
                    }

                    MaintainRecord maintainRecord = maintainRecordMapper.get(Integer.parseInt(info.getRecordId()));
                    info.setMaintainRecord(maintainRecord);
                }
            }

        PageInfo<WorkInfo> pageInfo = new PageInfo<>(list);

        Map<String, Object> map = new HashMap<>();
        map.put("list", pageInfo.getList());
        map.put("total", pageInfo.getTotal());

        return Result.success(map);
    }

    @Override
    public Result get(int id) {
        WorkInfo workInfo = workInfoDao.get(id);
        return Result.success(workInfo);
    }
}
